﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using InHD.model;
using System.Windows.Input;
using InHD.commands;
using System.Collections.ObjectModel;
using InHD.dataaccess;
using System.Data;
using InHD.utilities;
using System.Windows;
using InHD.Properties;

namespace InHD.viewmodels
{
    class AccReceivableFormViewModel : WorkspaceViewModel
    {
        #region Constructor
        public AccReceivableFormViewModel(Transaction transaction, CompanyInfo companyInfo)
        {
            _transaction = transaction;
            _companyInfo = companyInfo;
            _packageRepo = new PackageRepository();            

            this._pacs = _packageRepo.GetPackgesByTransaction(_transaction.TransactionUNK);
        }
        #endregion

        #region Value Property
        private Transaction _transaction;
        public string commandExcute = string.Empty;
        private CompanyInfo _companyInfo;

        private PackageRepository _packageRepo;
        #endregion

        private double exTax, incTax, tax;
        bool _isWholesale;
        private List<Package> _pacs;

        #region Presentation Property

        public Transaction Transaction
        {
            get
            {
                return _transaction;
            }
        }

        public bool IsIncludeTax
        {
            get { return string.IsNullOrEmpty(this._transaction.TaxUNK) ? false : true; }
        }

        public string TotalPriceExTax
        {
            get
            {
                return Resources.Ex_Tax + ((long)(this.Transaction.TotalSaleAmount / (1 + _transaction.TaxPercentage))).ToString();
            }
        }

        public string TotalPriceTax
        {
            get
            {
                return !IsIncludeTax ? Resources.Tax_Title + " 0 %" : Resources.Tax_Title + ((long)(this.Transaction.TaxPercentage * 100)).ToString() + " %";
            }
        }

        public string TotalPriceIncTax
        {
            get
            {
                return Resources.Inc_Tax + ((long)this.Transaction.TotalSaleAmount).ToString();
            }
        }

        public bool IsWholesale
        {
            get { return this._isWholesale; }
        }


        public List<Package> PackagesCollection
        {
            get
            {
                return this._pacs;
            }
            set
            {
                if (_pacs != value)
                {
                    this._pacs = value;
                    OnPropertyChanged("PackagesCollection");
                }
            }
        }

        public string Tax
        {
            get
            {
                return this._transaction.TaxName;
            }
        }
        public string CustomerName
        {
            get
            {
                return this._transaction.CustomerFirstName + " " + this._transaction.CustomerLastName;
            }
        }

        #endregion

        #region Command
        private RelayCommand _closeCommand;
        public ICommand CancelCommand
        {
            get
            {
                if (_closeCommand == null)
                {
                    _closeCommand = new RelayCommand(
                        (param) => this.Close());
                }
                return _closeCommand;
            }
        }

        private RelayCommand _getAccReceivableCommand;
        public ICommand GetAccReceivableCommand
        {
            get
            {
                if (_getAccReceivableCommand == null)
                {
                    _getAccReceivableCommand = new RelayCommand(
                        (param) => this.GetAccReceivable());
                }
                return _getAccReceivableCommand;
            }
        }

        #endregion

        #region Command Method
        void Close()
        {
            commandExcute = "CloseTransactionDetail";
            OnRequestClose();
        }

        void GetAccReceivable()
        {
            PreparePrint();

            if (Transaction.TotalSaleAmount < 200)
            {
                if (MessageBox.Show(Resources.Ask_Receive_invoice, Resources.App_Title, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    DoPrint();
                }
            }
            else
            {
                DoPrint();
            }


            TransactionRepository _transRepo = new TransactionRepository();
            _transRepo.DeleteTransaction(Transaction.TransactionUNK);

            commandExcute = "GetAccReceivable";
            OnRequestClose();
        }

        private RegisterPrintingRepository _regRepo = new RegisterPrintingRepository();
        private InvoicePrinter _invoicePrinter;
        private bool PreparePrint()
        {
            DataRow regRow = this._regRepo.CheckRegisterExistenceByInvoiceTpl(this._transaction.InvoiceTemplateUnk);
            if (regRow == null) return false;

            int maxNumberOfUse = Convert.ToInt16(regRow["maxUsingTimes"]);
            int remainUse = Convert.ToInt16(regRow["number"]);
            int regID = Convert.ToInt16(regRow["id"]);
            string spanKH01 = Convert.ToChar(regID / 26 + 65).ToString() + Convert.ToChar(regID % 26 + 65).ToString();

            string tableName = "tableContent";
            string[] listColumn = { "1", "2", "3", "4", "5", "6" };
            DataTable dataTable = new DataTable();
            foreach (string col in listColumn)
            {
                dataTable.Columns.Add(col);
            }

            int count = 0;
            foreach (Package pack in PackagesCollection)
            {
                count++;
                DataRow row = dataTable.NewRow();
                row[0] = count;
                row[1] = pack.ProductName;
                row[2] = "N/A";
                row[3] = pack.Quantity;
                row[4] = pack.UnitPrice;
                row[5] = pack.PackagePrice;
                dataTable.Rows.Add(row);
            }

            _invoicePrinter = new InvoicePrinter(this._transaction.InvoiceTemplateUnk);
            _invoicePrinter.PutDataTable(tableName, dataTable);
            _invoicePrinter.PutSpan("spanMS01", "02GTTT2");
            _invoicePrinter.PutSpan("spanMS02", regID.ToString());
            _invoicePrinter.PutSpan("spanKH01", spanKH01);
            _invoicePrinter.PutSpan("spanKH02", Convert.ToInt16(DateTime.Now.Year) - 2000 + "T");
            _invoicePrinter.PutSpan("spanNumber", (maxNumberOfUse - remainUse + 1).ToString().PadLeft(7, '0'));
            _invoicePrinter.PutSpan("spanDay", DateTime.Now.Day.ToString().PadLeft(2, '0'));
            _invoicePrinter.PutSpan("spanMonth", DateTime.Now.Month.ToString());
            _invoicePrinter.PutSpan("spanYear", DateTime.Now.Year.ToString());
            _invoicePrinter.PutSpan("spanCompanyName", _companyInfo.Name);
            _invoicePrinter.PutSpan("spanTaxCode", _companyInfo.Taxcode);
            _invoicePrinter.PutSpan("spanAddress", _companyInfo.Address);
            _invoicePrinter.PutSpan("spanPhone", _companyInfo.Phone);
            _invoicePrinter.PutSpan("spanCustomerName", Transaction.CustomerFirstName + " " + Transaction.CustomerLastName);
            CustomerRepository _cusRepo = new CustomerRepository();
            _cusRepo.LoadAllCustomers();
            Customer customer = _cusRepo.GetProductsWthSearchCriteria("CustomerUNK", Transaction.CustomerUnk)[0];
            _invoicePrinter.PutSpan("spanCustomerCompany", customer.Company);      
            _invoicePrinter.PutSpan("spanCustomerAddress", customer.Address);
            _invoicePrinter.PutSpan("spanPaymentType", this.Transaction.PaymentType.Equals(PaymentTypes.Cash) ? "Tiền mặt" : "Chuyển khoản");
            _invoicePrinter.PutSpan("spanTotal", ((long)Math.Round(this.Transaction.TotalSaleAmount)).ToString());
            _invoicePrinter.PutSpan("spanTotalText", utilities.Utilities.ReadVND((long)Math.Round(this.Transaction.TotalSaleAmount)));
            return true;
        }

        private void DoPrint()
        {
            _invoicePrinter.PutSpan("spanLien", Resources.Print_Lien1);
            _invoicePrinter.Print(true);
            _invoicePrinter.PutSpan("spanLien", Resources.Print_Lien2);
            _invoicePrinter.Print(false);
        }
        #endregion

        
    }
}
